package com.sgai.zero_robot.ui.control;

import android.graphics.Bitmap;
import com.sgai.zero_robot.ui.history.RunnableCallBack;
import com.sgai.zero_robot.utils.LogUtil;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class SaveBitmapRunnable implements Runnable {
    private final RunnableCallBack<String> callBack;
    private final File file;
    private final Bitmap bitmap;

    public SaveBitmapRunnable(File file, Bitmap bitmap, RunnableCallBack<String> callBack) {
        this.callBack = callBack;
        this.bitmap = bitmap;
        this.file = file;
    }

    @Override
    public void run() {
        File dir = file.getParentFile(); // /sdcard/Android/data/<包名>/files/MyCaptures/
        if (dir != null && !dir.exists()) {
            dir.mkdirs();
        }

        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
            LogUtil.d("SaveBitmap", "图片已保存: " + file.getAbsolutePath());
            if (callBack!=null){
                callBack.onResult(file.getAbsolutePath());
            }
        } catch (Exception e) {
            e.printStackTrace();
            if (callBack!=null){
                callBack.onResult(null);
            }
        } finally {
            if (out != null) {
                try { out.close(); } catch (IOException ignored) {}
            }
        }
    }
}